package com.huluobo.hyj.hyjmodel.contract.addFriend

import cn.bmob.v3.BmobQuery
import cn.bmob.v3.BmobUser
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import com.huluobo.hyj.hyjmodel.data.AddFriendItem
import com.huluobo.hyj.hyjmodel.data.db.IMDatabase
import com.hyphenate.chat.EMClient
import org.jetbrains.anko.doAsync

/**
 *@author : USER
 *@date : 2020/9/17 16:00
 *@params :
 *@description:
 */
class AddFriendPresenter(val view:AddFriendContract.View) :AddFriendContract.Presenter {
   val addFriendItems = mutableListOf<AddFriendItem>()
    //搜索用户
    override fun search(key: String) {
        //需要完成model层，搜索并返回model
        val query = BmobQuery<BmobUser>()
        query.addWhereContains("username",key) //找到在Bmob中的表
            .addWhereNotEqualTo("username",EMClient.getInstance().currentUser) //首先把自己去除
        //开始查询
        query.findObjects(object :FindListener<BmobUser>(){
            override fun done(list: MutableList<BmobUser>?, e: BmobException?) {
                if(e == null){
//                    Log.i("TAg","list:${list?.size}")
                    //创建AddFriendItem的集合
                    val allContracts  = IMDatabase.instance.getAllContacts()
                    //生成数据模型
                    doAsync {  //耗时操作子线程中运行
                        list?.forEach {
                            //对比是否已经添加过好友
                            var isAdded = false
                            for (contact in allContracts){
                                if(contact.name == it.username){
                                    isAdded = true
                                }
                            }

                            val addFriendItem = AddFriendItem(it.username,it.createdAt,isAdded)
                            addFriendItems.add(addFriendItem)
                        }
                        runOnUiThread { view.onSearchSuccess() }
                    }
                }else view.onSearchFailed()
            }

        })
    }
}